import { App } from "../../../../src/App";
import PackSys from "../../../src/system/PackSys";
import PropSys from "../../../src/system/PropSys";
import { GameModule, LandlordEvents } from "../Game/GameModule";

const { ccclass, property } = cc._decorator;
const MAX_COUNT:number = 16;
@ccclass
export default class UserInfoView extends cc.Component {

    @property(cc.Label)
    lblName: cc.Label = null;
    @property(cc.Label)
    lblFlag: cc.Label = null;
    @property(cc.Label)
    lblScore: cc.Label = null;
    @property(cc.Label)
    lblRank: cc.Label = null;
    @property(cc.Sprite)
    imgHead: cc.Sprite = null;
    @property(cc.Node)
    btnBind: cc.Node = null;
    @property(cc.Node)
    imgBestRank: cc.Node = null;
    @property(cc.RichText)
    lblTips: cc.RichText = null;
    
    // 背包
    @property(cc.PageView)
    pageView: cc.PageView = null;
    @property(cc.Node)
    pageNode: cc.Node = null;
    @property(cc.Node)
    item: cc.Node = null;
    
    private _timeID:number = null;
    private _pageContainer:cc.Node = null;
    onLoad() {
        const userData = GameModule.userInfo;
        this.lblName.string = userData.UserName;
        this.lblScore.string = `${App.Util.formatScore(userData.Coin)}`;
        this.lblFlag.string = GameModule.userTitle(userData.Coin);
        App.Avatar.setHead(userData.Avatar, this.imgHead);
        const str = App.getText(GameModule.isSingle ?  'landlord.watch_viedo0' : 'landlord.watch_viedo1');
        const rewards = App.getCfg('reward'); 
        this.lblTips.string = App.Util.format(str,rewards[GameModule.isSingle?0:1]);
        this._pageContainer = this.pageNode.parent;
        this.pageNode.parent = null;
    };

    start(){
        const userData = GameModule.userInfo;
        const rank = GameModule.rankInfo;
        rank.length > 0 && (this.imgBestRank.active = GameModule.rankInfo[0].openID === userData.OpenID);
        if (!this.imgBestRank.active){
            GameModule.rankInfo.forEach((it,idx)=>{
                if (it.openID === userData.OpenID){
                    this.lblRank.node.active = true;
                    this.lblRank.string = App.Util.format(App.getText('landlord.rank_number'),idx+1);
                    return ;
                }
            });
        }

        let _date = new Date();
        App.setLableText(this.node,'timeNode/lblMonth',App.Util.PrefixZero(_date.getMonth()+1,2));
        App.setLableText(this.node,'timeNode/lblDay',App.Util.PrefixZero(_date.getDate(),2));
        App.setLableText(this.node,'timeNode/lblHour',App.Util.PrefixZero(_date.getHours(),2));
        App.setLableText(this.node,'timeNode/lblMinute',App.Util.PrefixZero(_date.getMinutes(),2));
        this._timeID = setInterval(() => {
            const now = new Date();
            now.getDate() !== _date.getDate() && App.setLableText(this.node,'timeNode/lblDay',App.Util.PrefixZero(now.getDate(),2));
            now.getHours() !== _date.getHours() && App.setLableText(this.node,'timeNode/lblHour',App.Util.PrefixZero(now.getHours(),2));
            now.getMinutes() !== _date.getMinutes() && App.setLableText(this.node,'timeNode/lblMinute',App.Util.PrefixZero(now.getMinutes(),2));
        }, 1000);

        // 设置背包
        this.pageNode.removeAllChildren();
        this._setItem(PackSys.containers);
    }

    onClicket(){
        App.Event.emit(LandlordEvents.EC_WATCH_VIDEO);
    }

    onDestroy(){
        clearInterval(this._timeID);
        this._timeID = null;
    }

    onItemClick(_, data) {
        cc.log(data);
        const it = JSON.parse(data);
        it && PackSys.useProp(it.id,1,(flag:number,goods:any)=>{
            flag === 0 && this._setItem(goods);
        });
    }

    private _setItem(goods: any[]) {
        if (!goods || goods.length < 1) return ;
        this.pageView.removeAllPages();
        let page = Math.ceil(goods.length/MAX_COUNT);
        page < 1 && (page = 3);
        for (let i = 0; i < page; ++i){
            const page = cc.instantiate(this.pageNode);
            this.pageView.addPage(page);
            for (let j = 0; j < MAX_COUNT; ++j){
                const item = cc.instantiate(this.item);
                const data = goods[i*MAX_COUNT+j];
                if (data){
                    PropSys.setIcon(data.id,item.getChildByName('imgIcon').getComponent(cc.Sprite));
                    App.setLableText(item,'lblCount',`X${data.count}`);
                    const clickEvent = new cc.Component.EventHandler();
                    clickEvent.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
                    clickEvent.component = 'UserInfo';// 这个是代码文件名
                    clickEvent.handler = 'onItemClick';
                    clickEvent.customEventData = JSON.stringify(data);
                    item.getComponent('TouchNode').clickEvent = clickEvent;
                } else {
                    item.getChildByName('imgIcon').getComponent(cc.Sprite).spriteFrame = null;
                    item.getChildByName('lblCount').getComponent(cc.Label).string = '';
                }
                page.addChild(item);
            }
        }
    }
}